package webfluxclient.handler;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import webfluxclient.bean.MethodInfo;
import webfluxclient.bean.ServerInfo;
import webfluxclient.interfaces.RestHandler;

public class RestHandlerImpl implements RestHandler {
    private WebClient client;

    @Override
    public void init(ServerInfo serverInfo) {
        client = WebClient.create(serverInfo.getUrl());
    }

    @Override
    public Object invokeRest(ServerInfo serverInfo, MethodInfo methodInfo) {
        Object result = null;
        WebClient.RequestBodySpec requestBodySpec = client
                //请求方法
                .method(methodInfo.getMethod())
                //请求url和参数
                .uri(methodInfo.getUrl(), methodInfo.getParams())
                //
                .accept(MediaType.APPLICATION_JSON);
        WebClient.ResponseSpec request = null;
        if (methodInfo.getBody() != null) {
            request = requestBodySpec.body(methodInfo.getBody(), methodInfo.getBodyElementType()).retrieve();
        } else {
            request = requestBodySpec.retrieve();
        }
        //异常处理
        request.onStatus(status -> status.value() == 404,
                response -> Mono.just(new RuntimeException("Not Found By WzyMongodb")));

        //处理规格
        if (methodInfo.isReturnFlux()) {
            result = request.bodyToFlux(methodInfo.getReturnElementType());
        } else {
            result = request.bodyToMono(methodInfo.getReturnElementType());
        }
        return result;
    }
}
